<template>
  <div>
    <van-form>
      <van-search v-model="word" @search="setCharacter"></van-search>
    </van-form>
    <div class="panel">
      <div class="py">{{ py }}</div>
      <div ref="character" class="character" id="character-target-div"></div>
    </div>
    <div class="btns">
      <van-row :gutter="10">
        <van-col :span="12">
          <van-button @click="animateCharacter" type="info" round block> 查看笔顺 </van-button>
        </van-col>
        <van-col :span="12">
          <van-button @click="quizCharacter" round block type="primary"> 练一练 </van-button>
        </van-col>
      </van-row>
    </div>
  </div>
</template>

<script>
import HanziWriter from "hanzi-writer";
import { pinyin } from "pinyin-pro";

let writer;
export default {
  data() {
    return {
      word: "我",
      py: "",
    };
  },
  methods: {
    renderCharacter(word) {
      const ref_character = this.$refs.character;
      writer = HanziWriter.create(ref_character, word, {
        padding: 5,
        radicalColor: "#168F16", // green
        delayBetweenLoops: 3000,
      });
      this.setPingYin(word);
      //   console.log(writer);
    },
    setPingYin(word) {
      const py = pinyin(word);
      this.py = py;
      return py;
    },
    setCharacter(word) {
      //   console.log(word);
      if (word.length === 1) {
        writer.setCharacter(word);
        this.setPingYin(word);
      }
    },
    quizCharacter() {
      writer.quiz();
      this.$toast("请在格子里手写一下试试吧");
    },
    animateCharacter() {
      writer.loopCharacterAnimation();
    },
  },
  created() {},
  mounted() {
    this.renderCharacter(this.word);
  },
};
</script>
<style lang="less" scoped>
.panel {
  border: 1px solid #eee;
  padding: 20px;
  width: 350px;
  margin: 0 auto;
  text-align: center;
  border-radius: 5px;
  margin-bottom: 10px;
}
.py {
  font-size: 50px;
  margin-bottom: 10px;
}
.character {
  display: inline-block;
  width: 200px;
  height: 200px;
  border: 1px solid #ccc;
  //   margin: 0 auto;
}
.btns {
  padding: 20px;
}
</style>
